<?php 
class Common {
	static public function array_insert ($array, $pos, $val) {
	    $array2 = array_splice($array,$pos);
	    $array[] = $val;
	    $array = array_merge($array,$array2);
	    
	    return $array;
	}
	
	static function startsWith($haystack, $needle) { // 这个函数 原来是放在Lng里面的
  		$length = strlen($needle);
  		return (substr($haystack, 0, $length) === $needle);
	}

	static public function string_start_with($string, $test)
	{
		$strlen = strlen($string);
	    $testlen = strlen($test);
	    if ($testlen > $strlen) return false;
	    return (strncmp($string, $test, $testlen) == 0);
	}
	
	static public function string_end_with($string, $test) {
	    $strlen = strlen($string);
	    $testlen = strlen($test);
	    if ($testlen > $strlen) return false;
	    return substr_compare($string, $test, -$testlen) === 0;
	}
	
	static public function string_has_any($string, $array) {
		foreach ($array as $m){
			if(strstr($string,$m)) return true;
		}
		return false;
	}
	
	static public function sendMsg($memcache, $target_type, $target_id, $msg) { 
		$timestamp=time();
		$a=$timestamp;$b=microtime();$b=substr($b,2,2);$c=$a.$b;
		//use mysql
		//$query="INSERT INTO blte_lines VALUES(".$c.",0,'',".$timestamp.",'".$broadcast."','','',0,0)";
		//$db->query($query);
		//use memcached
		$mkey = (string)"sys".$target_type."_".$target_id;
		$mmsg = array($c,0,'',$target_type,$target_id,$msg,'',0);
		$cache = new Cache();
		$mlines = $cache->get($mkey);
		if(!$mlines) {
			//the first chat msg
			$mlines = array($mmsg);
			$cache->set($mkey, $mlines);
		} else {
			$mlines = (array)$mlines;
			array_push($mlines, $mmsg);//顺序：从新到旧
			while(count($mlines) > 10) {
				array_shift($mlines);
			}
			$cache->set($mkey, $mlines);
		}
	}
	
	static public function broadcastMsg($broadcast) { 
		$timestamp=time();
		$a=$timestamp;$b=microtime();$b=substr($b,2,2);$c=$a.$b;
		//use mysql
		//$query="INSERT INTO blte_lines VALUES(".$c.",0,'',".$timestamp.",'".$broadcast."','','',0,0)";
		//$db->query($query);
		//use memcached
		$mkey = "sys0_0";
		$mmsg = array($c,0,'',0,0,$broadcast,'',0);
		$cache = new Cache();
		$mlines = $cache->get($mkey);
		if (!$mlines) {
			//the first chat msg
			$mlines = array($mmsg);
			$cache->set($mkey, $mlines);
		} else {
			$mlines = (array)$mlines;
			array_push($mlines, $mmsg);//顺序：从新到旧
			while(count($mlines) > 10) {
				array_shift($mlines);
			}
			$cache->set($mkey, $mlines);
		}
	}
	
	/**
	 * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8). 
	 * Modified function from http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps
	 * Modified by derek wang to fix ISO-8859-1 issue
	 *
	 * @param string $source escaped with Javascript's escape() function
	 * @param string $iconv_to destination character set will be used as second paramether in the iconv function. Default is UTF-8.
	 * @return string
	 */
	static public function unescape($source, $iconv_to = 'UTF-8') {
		//first, convert all %FF like escape code into char
		$source = urldecode($source);
		//decode string into utf-8, then the string will only have %uFFFF escape code
		$source = iconv("ISO-8859-1", "UTF-8", $source);
		
	    $decodedStr = '';
	    $pos = 0;
	    $len = strlen ($source);
	    while ($pos < $len) {
	        $charAt = substr ($source, $pos, 1);
	        if ($charAt == '%') {
	            $pos++;
	            $charAt = substr ($source, $pos, 1);
	            if ($charAt == 'u') {
	                // we got a unicode character
	                $pos++;
	                $unicodeHexVal = substr ($source, $pos, 4);
	                $unicode = hexdec ($unicodeHexVal);
	                $decodedStr .= code2utf($unicode);
	                $pos += 4;
	            } else {
	                // we have an escaped ascii character
	                $hexVal = substr ($source, $pos, 2);
					$decodedStr .= '%'.$hexVal;
	                $pos += 2;
	            }
	        } else {
	            $decodedStr .= $charAt;
	            $pos++;
	        }
	    }
	
	    if ($iconv_to != "UTF-8") {
	        $decodedStr = iconv("UTF-8", $iconv_to, $decodedStr);
	    }
	    
	    return $decodedStr;
	}
	
	/**
	 * Function coverts number of utf char into that character.
	 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
	 *
	 * @param int $num
	 * @return utf8char
	 */
	static public function code2utf($num){
	    if ($num < 128) return chr($num);
	    if ($num < 2048) return chr(($num>>6)+192).chr(($num&63)+128);
	    if ($num < 65536) return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
	    if ($num < 2097152) return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
	    return '';
	}
	
	
	static public function pushMsg($codes, $text, $badge) {
		global $master_server;
		Curl::curl_post($master_server."internal/apns_api.php", "codes=".$codes."&text=".$text."&badge=".$badge);
	}
	
	static public function pushMsg2User($memcache, $db, $uid, $text, $badge) { //push message
	    $onlinetime = $memcache->get("online_".$uid);
		if (!$onlinetime || time()-$onlinetime>180) {
			$query_pushid=$db->query("select i_pushid,off from player_info where u_id=".$uid);//not online
			$list_pushid=$db->fetch_array($query_pushid);
			$pushid = $list_pushid['i_pushid'];
			if ($pushid != NULL && strlen($pushid) == 73) {
				if ($list_pushid['off'] == 0) { //帐号是否被禁
					$pushid_chars=array("<",">"," "); //apple push message
			  	foreach ($pushid_chars as $mchar) { //replace
			       $pushid = str_replace($mchar, '', $pushid);
			    }
			    pushMsg($pushid, $text, $badge);
			  }
			}
		}
	}
	
	static public function pushMsg2Users($memcache, $db, $uids, $text, $badge) {//group push message
		$nowtime = time();
		$pushids=NULL;
		$count=0;
		$cache = new Cache();
		foreach ($uids as $uid) {
			$onlinetime = $cache->get("online_".$uid);
			if (!$onlinetime || $nowtime-$onlinetime>180) {
				//not online
				$query_pushid=$db->query("select i_pushid,off from player_info where u_id=".$uid);
				$list_pushid=$db->fetch_array($query_pushid);
				$pushid = $list_pushid['i_pushid'];
				if ($pushid != NULL && strlen($pushid) == 73) {
					if ($list_pushid['off'] == 0) {//帐号是否被禁
						$pushid_chars=array("<",">"," ");//apple push message
					  	foreach ($pushid_chars as $mchar){
					       $pushid = str_replace($mchar, '', $pushid); //replace
					    }
					    if ($pushids==NULL)	{
							$pushids=$pushid;
						} else {
							$pushids=$pushids.",".$pushid;
						}
						if ($count > 200) {
							pushMsg($pushids, $text, $badge);
							$pushids=NULL;
							$count=0;
						} else {
							$count++;
						}
					}
				}
			}
		}
		if ($pushids != NULL) {
			pushMsg($pushids, $text, $badge);
		}
	}
	
	static public function getPushId($memcache, $uid, $pushid) {
		$nowtime = time();
		$cache = new Cache();
		$onlinetime = $cache->get("online_".$uid);
		if (!$onlinetime || $nowtime-$onlinetime > 180) {
			if ($pushid != NULL && strlen($pushid) == 73) {//not online
				$pushid_chars=array("<",">"," ");//apple push message
			  	foreach ($pushid_chars as $mchar) {
			       $pushid = str_replace($mchar, '', $pushid); //replace
			    }
		    	return $pushid;//echo $pushid." - in func\n";
		  }
		}
		return NULL;
	}
	
	static public function pushMsg2Users2($pushids, $text, $badge) {//group push message
		$count=0;
		$pushidstr=NULL;
		foreach ($pushids as $pushid) {
	    	if ($pushidstr==NULL) {
				$pushidstr=$pushid;
			} else {
				$pushidstr=$pushidstr.",".$pushid;
			}
			if ($count > 200) {
				pushMsg($pushidstr, $text, $badge);
				$pushidstr=NULL;
				$count=0;
			} else {
				$count++;
			}
		}
		if ($pushidstr!=NULL) {//echo $pushidstr."\n";
			pushMsg($pushidstr, $text, $badge);
		}
	}
	
	static public function EMail($type,$to,$params) {//email out
		global $master_server;
		return curl_get($master_server."internal/mail_api.php?type=".$type."&to=".$to."&params=".urlencode(json_encode($params)));
	}
	
	static public function ticktMail($uname,$params) {//send a mail to ticket system via mail system.
		global $master_server;
		return curl_get($master_server."internal/ticketmail_api.php?type=0&to=:help&uname=".$uname."&params=".urlencode(json_encode($params)));
	}
	
	static public function IngameMail($memcache, $db,$e_recvid, $e_recver, $e_title, $e_text) {
		IngameMail2($memcache, $db,$e_recvid, $e_recver, $e_title, $e_text, "sys");
	}
	
	static public function IngameMail2($memcache, $db,$e_recvid, $e_recver, $e_title, $e_text, $sender) {
		global $lng_data;
		$db->query("INSERT INTO `mail` ( `e_sendid` , `e_sender` , e_recvid, `e_recver` , `e_title` , `e_text` , `e_times` , `e_read`) 
	     VALUES ('0', '".$sender."', '".$e_recvid."', '".$e_recver."', '".$e_title."', '".$e_text."', '".time()."', '0');");    
			//设置1个event: typeid=2，表示有新邮件
	    $eventmsg = array("typeid"=>2);
	    $cache = new Cache();
	    $events = $cache->get("e_".$e_recvid);
	    if (!$events) {
	    	$events = array($eventmsg);
	    } else {
	    	array_push($events, $eventmsg);
	    }
	    $cache->set("e_".$e_recvid, $events);
	    //push message
	    $uid=$e_recvid;
	    $text="[".$lng_data['system']." ".$lng_data['to']." ".$e_recver."] ".$e_title;
	    $badge=1;
	    self::pushMsg2User( $db, $uid, $text, $badge);
	}
	
	static public function getLng($player_info) {
		if (!array_key_exists("lng",$player_info) || !$player_info['lng'] || $player_info['lng']=='') {
			return "en";
		}
		return $player_info['lng'];
	}
	
	static public function checkPlayerInfo($player_info) {
		if (!$player_info) {
			return 2;
		}
		
		if ($player_info['p_nickname'] == '') {
			return 5;
		}
		if ($player_info['off'] == 1) {
			return 14;
		}
		return 0;
	}
	
	static public function cashLog($options) { //元宝变动信息
		$db = new Data();
		$db->insertData('cash_log', $options);
	}
	
	static public function luckExt($num,$max_num=100) { //几率计算
		if ( $num <= 0 ) {
			return false;
		}
		$rand = rand(0, $max_num);
		$num = $num * $max_num;
		if ( $num > $max_num ) {
			return true;
		}
		if ( $rand <= $num ) {
			return true;
		}
		return false;
	}
	
	static public function listSortBy($list,$field, $sortby='asc') { //排序
	   if(is_array($list)){
	       $refer = $resultSet = array();
	       foreach ($list as $i => $data)
	           $refer[$i] = &$data[$field];
	       switch ($sortby) {
	           case 'asc': // 正向排序
	                asort($refer);
	                break;
	           case 'desc':// 逆向排序
	                arsort($refer);
	                break;
	           case 'nat': // 自然排序
	                natcasesort($refer);
	                break;
	       }
	       foreach ( $refer as $key=> $val)
	           $resultSet[] = &$list[$key];
	       return $resultSet;
	   }
	   return false;
	}
}
?>